import { useNavigation } from "@react-navigation/native";
import { forwardRef, useImperativeHandle, useRef } from "react";
import {
  Dimensions,
  Image,
  StyleSheet,
  Text,
  TouchableNativeFeedback,
  View,
} from "react-native";
import Animated, {
  runOnJS,
  useAnimatedStyle,
  useSharedValue,
  withDelay,
  withTiming,
} from "react-native-reanimated";
import Icon from "react-native-vector-icons/AntDesign";

const screenWidth = Dimensions.get("window").width;

export interface CartoonSearchViewRef {
  playAnimation: () => void;
}

interface CartoonSearchViewProps {
  cartoonList: any;
}

const CartoonSearchView = forwardRef<
  CartoonSearchViewRef,
  CartoonSearchViewProps
>(({ cartoonList }, ref) => {
  const navigation = useNavigation();

  const searchBarWidth = useSharedValue(screenWidth - 30);
  const imageTranslate = Array(3)
    .fill(0)
    .map(() => useSharedValue(30));
  const imageOpacity = Array(3)
    .fill(0)
    .map(() => useSharedValue(0));
  const normalRef = useRef(true);

  useImperativeHandle(ref, () => ({
    playAnimation,
  }));

  const playAnimation = () => {
    if (normalRef.current) {
      searchBarWidth.value = screenWidth - 160;
      runOnJS(requestAnimationFrame)(() => {
        animateImages();
      });
    } else {
      searchBarWidth.value = screenWidth - 30;
      resetImages();
    }
    normalRef.current = !normalRef.current;
  };

  const imageAnimatedStyles = imageTranslate.map((translate, index) =>
    useAnimatedStyle(() => ({
      transform: [
        { translateX: -translate.value },
        { translateY: translate.value },
      ],
      opacity: imageOpacity[index].value,
    }))
  );

  const searchBarAnimation = useAnimatedStyle(() => {
    return {
      width: withTiming(searchBarWidth.value, { duration: 200 }),
    };
  });

  const animateImages = () => {
    "worklet";
    const animationDuration = 150;
    const delayFactor = 40;

    imageTranslate.forEach((translateY, index) => {
      translateY.value = withDelay(
        delayFactor * index,
        withTiming(0, { duration: animationDuration })
      );
      imageOpacity[index].value = withDelay(
        delayFactor * index,
        withTiming(1, { duration: animationDuration })
      );
    });
  };

  const resetImages = () => {
    "worklet";
    imageTranslate.forEach((translateY) => {
      translateY.value = withTiming(30, { duration: 300 });
    });
    imageOpacity.forEach((opacity) => {
      opacity.value = withTiming(0, { duration: 300 });
    });
  };

  return (
    <View style={styles.headerContainer}>
      <TouchableNativeFeedback
        background={TouchableNativeFeedback.Ripple("#e6e6e6", false)}
        onPress={() => {
          // @ts-ignore
          navigation.navigate("Search");
        }}
      >
        <Animated.View style={[styles.searchBar, searchBarAnimation]}>
          <Icon name="search1" size={20} color="rgba(0,0,0,0.3)" />
          <Text style={styles.searchInput}>搜索内容/角色</Text>
        </Animated.View>
      </TouchableNativeFeedback>
      <View
        style={{
          flexDirection: "row",
          position: "absolute",
          left: screenWidth - 150,
        }}
      >
        {cartoonList.map((cartoon: any, index: number) => (
          <Animated.Image
            key={index}
            style={[
              { width: 40, height: 40, borderRadius: 8, resizeMode: "cover" },
              imageAnimatedStyles[index],
            ]}
            source={{ uri: cartoon.avatar }}
          />
        ))}
      </View>
    </View>
  );
});

const styles = StyleSheet.create({
  headerContainer: {
    width: screenWidth - 30,
    height: 44,
    flexDirection: "row",
    alignItems: "center",
  },
  searchBar: {
    backgroundColor: "rgba(0,0,0,0.06)",
    height: 36,
    borderRadius: 6,
    justifyContent: "flex-start",
    alignItems: "center",
    paddingHorizontal: 10,
    flexDirection: "row",
  },
  searchInput: { color: "rgba(0,0,0,0.3)", marginLeft: 5, fontSize: 14 },
});

export default CartoonSearchView;
